<template>
  <div>
    <el-backtop :right="100" :bottom="200" :visibility-height="10" />
    <!-- 搜索 -->
    <el-space wrap style="margin-bottom:10px">
      <el-input v-model="title" placeholder="请输入商品名称" clearable />
      <el-input v-model="id" placeholder="请输入团购ID" clearable />
      <el-select v-model="status" placeholder="请选择团购状态" clearable>
        <el-option
          v-for="item in ostatus"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" :icon="Search" @click="listData">查找</el-button>
      <el-button type="primary" :icon="Edit" @click="Add">添加</el-button>
    </el-space>
    <!-- 列表 -->
    <el-table :data="tableData" border>
      <el-table-column type="expand">
        <template #default="scope">
          <div style="width: 95%;margin:auto">
            <span style="color:#99A9BF;margin-right:45px">类目ID</span>
            <span>{{scope.row.categoryId}}</span>
            <p style="color:#99A9BF">商品sku属性</p>
            <el-table :data="scope.row.groupShopSkuDTOList" border style="width: 100%;">
              <el-table-column prop="skuId" label="SkuId" align="center" />
              <el-table-column prop="title" label="规格标题" align="center" />
              <el-table-column prop="skuGroupShopPrice" label="团购价格(元)" align="center" />
              <el-table-column prop="stock" label="库存" align="center" />
              <el-table-column prop="originalPrice" label="原始价格(元)" align="center" />
              <el-table-column prop="vipPrice" label="会员价格(元)" align="center" />
              <el-table-column prop="barCode" label="国际条码" align="center" />
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="团购ID" align="center" />
      <el-table-column prop="spuId" label="商品ID" align="center" />
      <el-table-column prop="title" label="商品名称" align="center" />
      <el-table-column prop="img" label="商品主图" align="center">
        <template #default="scope">
          <img :src="scope.row.img" class="el-table-column-img" />
        </template>
      </el-table-column>
      <el-table-column prop="sales" label="未满策略" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.sales==0?'warning':''">{{scope.row.sales==0?'发货':''}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="活动状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status?'success':'primary'">{{scope.row.status?'进行':'冻结'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="gmtStart" label="开始时间" align="center">
        <template #default="scope">
          {{ scope.row.gmtStart?timestampToTimeT(scope.row.gmtStart):''}}
          {{ scope.row.gmtStart?timestampToTimeS(scope.row.gmtStart):''}}
        </template>
      </el-table-column>
      <el-table-column prop="gmtEnd" label="结束时间" align="center">
        <template #default="scope">
          {{ scope.row.gmtEnd?timestampToTimeT(scope.row.gmtEnd):''}}
          {{ scope.row.gmtEnd?timestampToTimeS(scope.row.gmtEnd):''}}
        </template>
      </el-table-column>
      <el-table-column prop="buyerNum" label="当前人数" align="center" />
      <el-table-column prop="minNum" label="目标人数" align="center" />
      <el-table-column align="center" label="操作" width="180">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 抽屉 -->
    <el-drawer
      v-model="drawer"
      :title="drawerTitle"
      direction="ltr"
      size="50%"
      :before-close="handleClose"
    >
      <el-space direction="vertical" fill="true">
        <el-card class="box-card">
          <p class="drawer-form-title">商品属性(spu)</p>
          <el-form
            :model="form"
            ref="ruleFormRef"
            :rules="rules"
            label-width="100px"
            label-position="left"
            class="drawer-form"
          >
            <el-form-item label="团购商品">
              <el-cascader
                v-model="form.categoryId"
                :options="options"
                :props="props"
                @change="productDetail"
              />
            </el-form-item>
            <el-form-item label="团购时间" prop="nickname">
              <el-config-provider :locale="locale">
                <el-date-picker
                  v-model="form.gmtStart"
                  type="datetime"
                  placeholder="请选择开始时间"
                  format="YYYY/MM/DD hh:mm:ss"
                  value-format="x"
                />至
                <el-date-picker
                  v-model="form.gmtEnd"
                  type="datetime"
                  placeholder="请选择结束时间"
                  format="YYYY/MM/DD hh:mm:ss"
                  value-format="x"
                />
              </el-config-provider>
            </el-form-item>
            <el-form-item label="团购基础人数">
              <el-input-number
                v-model="form.minNum "
                :min="1"
                controls-position="right"
                @change="handleChange"
              />
            </el-form-item>
            <el-form-item label="活动结束时人数没有达到基础人数采取：" prop="password">
              <span>
                <el-button
                  class="el-form-item-days"
                  :type="form.automaticRefund==1?'primary':''"
                  @click="form.automaticRefund=1"
                >不要退款，我要发货</el-button>
                <el-button
                  class="el-form-item-time"
                  :type="form.automaticRefund==0?'primary':''"
                  @click="form.automaticRefund=0"
                >自动退款，我不发货</el-button>
              </span>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card class="box-card" style="width: 95%">
          <template #header>
            <div class="card-header">
              <span>商品类型(sku)</span>
              <el-popover placement="bottom" :width="300" trigger="click" ref="reference">
                <div style="white-space: nowrap;">
                  <span style="margin-right:40px">团购价格</span>
                  <el-input-number
                    v-model="numPrice"
                    :min="1"
                    controls-position="right"
                    @change="handleChange"
                  />元
                </div>
                <div style="text-align: right; margin: 0">
                  <el-button size="small" text @click="popoverCancel">取消</el-button>
                  <el-button size="small" type="primary" @click="popoverSubmit">确认</el-button>
                </div>
                <template #reference>
                  <el-button class="Batch-pricing-button">批量定价</el-button>
                </template>
              </el-popover>
            </div>
          </template>
          <!-- 商品类型（sku） -->
          <el-table :data="form.groupShopSkuList" border style="width: 100%;">
            <el-table-column prop="id" label="SkuId" align="center" />
            <el-table-column prop="barCode" label="Skut条形码" align="center" />
            <el-table-column prop="title" label="类型名" align="center" />
            <el-table-column prop="stock" label="库存" align="center" />
            <el-table-column prop="originalPrice" label="现价/元" align="center" />
            <el-table-column prop="skuGroupShopPrice" label="团购价格/元" align="center" />
            <el-table-column align="center" label="操作" width="100">
              <template #default="scope">
                <el-button size="small" type="primary" @click="handleToupdate(scope.row)">更新</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 修改弹框 -->
          <el-dialog v-model="dialogFormVisible" title="更新团购价格">
            <el-form
              :model="form"
              style="margin-left:40px"
              label-width="100px"
              label-position="left"
            >
              <el-form-item label="团购价格">
                <el-input-number
                  v-model="numPriceUpdate"
                  :min="1"
                  controls-position="right"
                  @change="handleChange"
                />元
              </el-form-item>
              <el-form-item label="现价">{{PriceUpdate}}元</el-form-item>
              <el-form-item label="sku类型名">{{skuTypeTitle}}</el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogFormVisible=false">取消</el-button>
                <el-button type="primary" @click="subMitUpdate">确定</el-button>
              </span>
            </template>
          </el-dialog>
        </el-card>
      </el-space>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer=false">取消</el-button>
          <el-button type="primary" @click="fangdou">{{subMitTutTitle}}</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 分页 -->
    <dome v-bind="domes" @limits="limits" @pages="pages" />
  </div>
</template>
<script>
import { post } from "@/util/http";
import dome from "@/components/DomeAndTop.vue";
import { Search, Edit } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import timestampToTimeT from "../../../timeformat/formatT";
import timestampToTimeS from "../../../timeformat/formatS";
import { ElMessageBox } from "element-plus";
import { ElConfigProvider } from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import { debounce } from "@/fangdou/fangdou";//防抖fangdou
export default {
  components: {
    dome,
    ElConfigProvider,
  },
  data() {
    return {
      Search,
      Edit,
      locale: zhCn,
      id: "", //搜索
      title: "",
      spuName: " ", //搜索---这里要空格，要传值
      status: "", //搜索
      supId: "",
      tableData: [], //列表
      drawer: false, //布尔值
      drawerTitle: "", //抽屉的标题
      subMitTutTitle: "",
      drawerDate: [], //抽屉--商品类型sku数据
      sales: true, //抽屉--商品属性是否发货的布尔值
      fill: true, //是否填充父容器
      form: {
        categoryId: "",
        gmtEnd: "",
        gmtStart: "",
        minNum: "",
        automaticRefund: 1, //团购人数未满是否自动退款
        groupShopSkuList: [], //团购sku链表
      },
      deId: "",
      visible: false, //批量定价的布尔值
      numPrice: "", //批量定价的值
      dialogFormVisible: false, //更新的弹框布尔值
      numPriceUpdate: "", //更新的团购价
      PriceUpdate: "", //更新的现价
      skuTypeTitle: "", //更新的sku类型名
      options: [], //类目数据
      // 类目的配置
      props: {
        value: "id",
        label: "label",
        children: "children",
        emitPath: false,
      },
      // 分页
      domes: {
        limit: 10,
        page: 1,
        total: 10,
      },
      //   用户状态
      ostatus: [
        {
          value: 0,
          label: "冻结",
        },
        {
          value: 1,
          label: "活动",
        },
      ],
    };
  },
  created() {
    this.listData();
    this.categoryData(); //商品类目
  },
  methods: {
    timestampToTimeT, //时间格式事件
    timestampToTimeS,
    handleClose() {
      ElMessageBox.confirm("你确定要关掉它吗?").then(() => {
        this.drawer = false;
      });
    },
    // 更新
    handleToupdate(e) {
      console.log(e, "更新的价钱");
      this.updateId = e.id;
      this.dialogFormVisible = true;
      this.numPriceUpdate = e.skuGroupShopPrice; //团购价
      this.PriceUpdate = e.originalPrice; //现价
      this.skuTypeTitle = e.title;
    },
    // 更新确定按钮
    subMitUpdate() {
      this.form.groupShopSkuList.find((item) => {
        if (item.id == this.updateId) {
          item.skuGroupShopPrice = this.numPriceUpdate;
        }
      });
      this.dialogFormVisible = false;
    },
    // 批量定价
    popoverSubmit() {
      if (this.numPrice) {
        this.form.groupShopSkuList.find((item) => {
          item.skuGroupShopPrice = this.numPrice;
          // item.vipPrice = this.numPrice;
        });
      }
      this.$refs.reference.hide(); //获取子节点然后隐藏元素
    },
    // 批量定价取消按钮
    popoverCancel() {
      this.$refs.reference.hide();
    },
    // 编辑
    handleEdit(e) {
      console.log(e, "编辑团购商品");
      Object.assign(this.form, {
        id: e.id,
        spuId: e.categoryId,
        gmtEnd: e.gmtEnd,
        gmtStart: e.gmtStart,
        minNum: e.minNum,
        automaticRefund: e.automaticRefund, //团购人数未满是否自动退款
        groupShopSkuList: e.groupShopSkuDTOList,
      });
      this.drawer = true;
      this.drawerTitle = "编辑团购商品";
      this.subMitTutTitle = "编辑";
      this.productDetail(e.spuId);
    },
    // 添加
    Add() {
      Object.assign(this.form, {
        categoryId: "",
        gmtEnd: "",
        gmtStart: "",
        minNum: "",
        automaticRefund: 1, //团购人数未满是否自动退款
        groupShopSkuList: [],
      });
      this.drawer = true;
      this.drawerTitle = "创建团购商品";
      this.subMitTutTitle = "创建";
    },
    // 商品详情
    productDetail(val) {
      let data = {
        _gp: "admin.product",
        _mt: "detail",
        spuId: val,
      };
      post(data).then((res) => {
        if (200 == res.data.errno) {
          this.form.groupShopSkuList = res.data.data.skuList; //商品详情列表
        } else {
          ElMessage.warning(res.data.errmsg);
        }
      });
    },
    // 类目列表
    categoryData() {
      let data = {
        _gp: "admin.product",
        _mt: "getSpuBigTree",
      };
      post(data)
        .then((res) => {
          if (200 == res.data.errno) {
            this.options = res.data.data;
          } else {
            ElMessage.warning(res.data.errmsg);
          }
        })
        .catch((err) => {
          ElMessage.error(err.data.errmsg);
        });
    },
    // 创建与编辑的提交
    subMit() {
      if (this.form.gmtStart > this.form.gmtEnd) {
        return ElMessage.warning("开始时间不能大于结束时间");
      }
      let groupShopSkuList = this.form.groupShopSkuList.map((item) => {
        return { skuId: item.id, skuGroupShopPrice: item.skuGroupShopPrice };
      });
      if (this.drawerTitle == "创建团购商品") {
        let data = {
          _gp: "admin.groupshop",
          _mt: "create",
          spuId: this.form.categoryId,
          gmtEnd: this.form.gmtEnd,
          gmtStart: this.form.gmtStart,
          minNum: this.form.minNum,
          automaticRefund: this.form.automaticRefund, //团购人数未满是否自动退款
          groupShopSkuList: JSON.stringify(groupShopSkuList),
        };
        post(data).then((res) => {
          if (200 == res.data.errno) {
            this.drawer = false;
            Object.assign(this.form, {
              categoryId: "",
              gmtEnd: "",
              gmtStart: "",
              minNum: "",
              automaticRefund: 1, //团购人数未满是否自动退款
              groupShopSkuList: [],
            });
            this.listData();
            ElMessage.success("团购创建成功");
          } else {
            ElMessage.warning(res.data.errmsg);
          }
        });
      } else {
        let data = {
          _gp: "admin.groupshop",
          _mt: "edit",
          id: this.form.id,
          spuId: this.form.categoryId,
          gmtEnd: this.form.gmtEnd,
          gmtStart: this.form.gmtStart,
          minNum: this.form.minNum,
          automaticRefund: this.form.automaticRefund, //团购人数未满是否自动退款
          groupShopSkuList: JSON.stringify(groupShopSkuList),
        };
        post(data).then((res) => {
          if (200 == res.data.errno) {
            this.drawer = false;
            Object.assign(this.form, {
              categoryId: "",
              gmtEnd: "",
              gmtStart: "",
              minNum: "",
              automaticRefund: 1, //团购人数未满是否自动退款
              groupShopSkuList: [],
            });
            this.listData();
            ElMessage.success("团购编辑成功");
          } else {
            ElMessage.warning(res.data.errmsg);
          }
        });
      }
    },
    fangdou: debounce(function () {
      this.subMit();
    }),
    listData() {
      let data = {
        _gp: "admin.groupshop",
        _mt: "list",
        id: this.supId,
        spuName: this.spuName,
        title: this.title,
        status: this.status,
        page: this.domes.page, //当前页码
        limit: this.domes.limit, //页码长度
      };
      post(data).then((res) => {
        if (200 == res.data.errno) {
          this.tableData = res.data.data.items;
          this.domes.total = res.data.data.total;
          console.log(res, "团购管理列表");
          ElMessage.success("团购请求成功");
        } else {
          ElMessage.warning(res.data.errmsg);
        }
      });
    },
    limits(e) {
      this.domes.limit = e;
      this.$nextTick(() => {
        this.listData();
      });
    },
    pages(e) {
      this.domes.page = e;
      this.$nextTick(() => {
        this.listData();
      });
    },
  },
};
</script>
<style lang="less" scoped>
.el-space .el-input {
  width: 240px;
}
.el-table-column-img {
  width: 50%;
}
// 抽屉样式
.Batch-pricing-button {
  float: right;
}
//
.el-form-item-days {
  border-radius: 4px 0px 0px 4px;
}
.el-form-item-time {
  border-radius: 0px 4px 4px 0px;
  margin-left: 0;
}
.update-input {
  border: 0px;
}
.drawer-form-title{
  font-weight: 700;
}
.drawer-form{
  margin-left: 50px;
}
</style>